package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study3.testcontroller;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study3.vo.UserEmployee;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/client")
public class HttpClientController {

    @GetMapping("/test1")
    public Map test1(UserEmployee employee) throws Exception {
        Map mres = new HashMap<>();
        // 默认配置创建一个httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpGet远程连接实例
        // 方式一  get请求传参
//        HttpGet httpGet = new HttpGet("http://localhost:8080/user/testGet?userName=a");
        // 拼接参数,可以用URIBuilder,也可以直接拼接在？传值，拼在url后面，如下--httpGet = new HttpGet(uri+"?id=123");

        // 方式二  get请求传参
        URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/user/testGet");
        uriBuilder.setParameter("userName","zs");
        URI uri = uriBuilder.build();

        HttpGet httpGet = new HttpGet(uri);
        // 设置配置请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(35000)// 连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 请求超时时间
                .setSocketTimeout(60000)// 数据读取超时时间
                .build();
        // 为httpGet实例设置配置
        httpGet.setConfig(requestConfig);
        try {
            // 执行get请求得到返回对象
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            String result = EntityUtils.toString(entity, "UTF-8");
            mres = JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return mres;
    }

    @PostMapping("/test2")
    public List test2() {
        List mres = new ArrayList();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://localhost:8080/user/testPost");
        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("userName", "Bob"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // writing error to Log
            e.printStackTrace();
        }
        /*
         * Execute the HTTP Request
         */
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                // EntityUtils to get the response content
                String content =  EntityUtils.toString(respEntity);
                mres = JSON.parseObject(content, List.class);
            }
        } catch (Exception e) {
            // writing exception to log
            e.printStackTrace();
        }
        return mres;
    }
    /**
     * post发送json字符串
     */
    @PostMapping("/test3")
    public Object test3() {
        String result = "";

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("http://localhost:8080/user/testPost1");
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            String params = "{\"userName\":\"David\"}";

            if (StringUtils.isNotBlank(params)) {
                httpPost.setEntity(new StringEntity(params, StandardCharsets.UTF_8));
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * post发送json字符串
     */
    @PostMapping("/test4")
    public Object test4() {
        String result = "";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("http://localhost:8080/user/testPost2");
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            String params = "[{\"userName\":\"a\",\"userAge\":\"b\",\"sex\":\"c\"}]";
            if (StringUtils.isNotBlank(params)) {
                httpPost.setEntity(new StringEntity(params, StandardCharsets.UTF_8));
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
//    URLEncoder.encode( URL, "UTF-8" )               URLDecoder.decode( URL, "UTF-8" )
}
